import api from './request';
import { Message } from 'element-ui';
// import fileDownload from 'js-file-download';
import { downloadFile } from '../utils/file';

/**
 * 文件上传
 * @description file format: xls/xlsx/doc/docx/pdf
 * @param { formData } data file formData
 * @returns { Array } file list
 *          [
 *            {
 *              createTime: "2021-11-18 12:05:20",
 *              fileId: 1461183718860128300,
 *              fileName: "test1.doc",
 *              filePath: "1637208320716_test1.doc",
 *              fileSize: 9216,
 *              fileSuffix: "doc",
 *              flag: null,
 *              standardId: null,
 *              updateTime: "2021-11-18 12:05:20",
 *              uploadTime: "2021-11-18 12:05:20",
 *            }
 *          ]
 */
export function uploadFile(data) {
  return api.request({
    url: '/common-controller/uploadFile',
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data;charset=UTF-8',
    },
    data,
  });
}

/**
 * 文件删除
 * @param { String } fileId  文件id
 */
export function deleteFile(fileId) {
  return api.request({
    url: '/common-controller/deleteFile',
    method: 'get',
    params: { fileId },
  });
}

/**
 * 根据id文件下载单个文件
 */
export function downloadFileById(id, fileName) {
  return new Promise((resolve, reject) => {
    api.request({
      url: '/common-controller/getFileById',
      method: 'get',
      responseType: 'blob',
      // responseType: 'arraybuffer',
      params: { id },
    })
      .then(res => {
        // fileDownload(res.data, fileName);
        downloadFile(res.data, fileName);
        resolve();
      })
      .catch(() => reject());
  });
}

/**
 * 根据ids下载多个文件的压缩包
 * @param { Array } ids 文件id
 * @param fileName 文件名称
 * @returns
 */
export function downloadMultipleFileByIds(ids, fileName = '附件压缩包.zip') {
  return new Promise((resolve, reject) => {
    api.request({
      url: '/common-controller/getFileByIds',
      method: 'post',
      responseType: 'arraybuffer',
      data: ids,
    })
      .then(res => {
        // fileDownload(res.data, fileName);
        downloadFile(res.data, fileName);
        resolve();
      })
      .catch(() => {
        Message({ type: 'error', message: '文件下载失败', duration: 3000 });
        reject();
      });
  });
}
